package com.ssy.lingxi.message.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.message.enums.MessageNoticeEnum;
import com.ssy.lingxi.message.enums.NoticeTemplateHeaderEnum;
import com.ssy.lingxi.message.model.dto.NoticeTemplateDTO;
import com.ssy.lingxi.message.service.ICommonService;
import com.ssy.lingxi.message.utils.MultiLanguageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * im - 业务实现层
 * @author fhj
 * @date 2021/03/22
 * @version 2.0.0
 */
@Slf4j
@Service
public class CommonServiceImpl implements ICommonService {

    @Value("${lingxi.notice.language}")
    private String language;

    @Override
    public void checkNoticeLanguage(){
        Map<String,NoticeTemplateDTO> noticeTemplateDTOS =null;
        if(StringUtils.hasLength(language)){
            //读取json文件
            Resource resource=new ClassPathResource(language+".json");
            if(!resource.exists()){
                log.error("请配置{}语言的通知模板",language);
                return;
            }
            try {
                ObjectMapper mapper = new ObjectMapper();
                List<NoticeTemplateDTO> templateDTOList = mapper.readValue(resource.getInputStream(), new TypeReference<List<NoticeTemplateDTO>>() {});
                if(CollectionUtil.isEmpty(templateDTOList)){
                    log.error("{}语言的消息模板为空，请配置",language);
                }else {
                    noticeTemplateDTOS=templateDTOList.stream().collect(Collectors.toMap(NoticeTemplateDTO::getMessageTemplateCode, v->v,(v1, v2)->v1));
                }
            } catch (Exception e) {
                log.error("检测消息多语言模板异常：",e);
            }
        }else{
            //默认中文
            noticeTemplateDTOS= MultiLanguageUtil.getDefaultMessageTemplate();
            log.info("启用默认语言消息模板");
        }
        if(CollectionUtil.isNotEmpty(noticeTemplateDTOS)){
            new MultiLanguageUtil(noticeTemplateDTOS);
            log.info("初始化多语言消息模板完成 language:{},共{}条 ",language,noticeTemplateDTOS.size());
        }else{
            log.warn("**************初始化多语言消息模板--失败**************");
        }
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) {
        List<Map<String, Object>> rows = Arrays.stream(MessageNoticeEnum.values()).map(message -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put(NoticeTemplateHeaderEnum.CODE.getMessage(), message.name());
            map.put(NoticeTemplateHeaderEnum.TITLE.getMessage(), message.getTitle());
            map.put(NoticeTemplateHeaderEnum.TARGET_TITLE.getMessage(), "");
            map.put(NoticeTemplateHeaderEnum.TEMPLATE.getMessage(), message.getTemplate());
            map.put(NoticeTemplateHeaderEnum.TARGET_TEMPLATE.getMessage(), message.getTemplate());
            return map;
        }).collect(Collectors.toList());
        ExcelWriter writer = ExcelUtil.getBigWriter();
        CellStyle style = writer.getHeadCellStyle();
        style.setWrapText(true);
        writer.write(rows);
        String fileName = "msg_template.xls";
        try (ServletOutputStream out = response.getOutputStream()) {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    @Override
    public void uploadNoticeTemplate(MultipartFile file) throws IOException {
        ExcelReader excel = ExcelUtil.getReader(file.getInputStream());
        //skip跳过表头内容
        List<NoticeTemplateDTO> collect = excel.read().stream().skip(1).map(o -> {
            NoticeTemplateDTO dto = null;
            MessageNoticeEnum messageNoticeEnum = MessageNoticeEnum.enumMap.get(o.get(NoticeTemplateHeaderEnum.CODE.getCode()).toString());
            if (messageNoticeEnum != null) {
                dto = new NoticeTemplateDTO();
                dto.setMessageTemplateCode(messageNoticeEnum.name());
                dto.setTarget(messageNoticeEnum.getTarget());
                dto.setBusinessType(messageNoticeEnum.getBusinessType());
                dto.setUrl(messageNoticeEnum.getUrl());
                dto.setAppUrl(messageNoticeEnum.getAppUrl());
                dto.setTitle(o.get(NoticeTemplateHeaderEnum.TARGET_TITLE.getCode()).toString());
                dto.setTemplate(o.get(NoticeTemplateHeaderEnum.TARGET_TEMPLATE.getCode()).toString());
            }
            return dto;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        log.info("\n复制以下内容，创建json文件放到resources目录下 命名与yml lingxi:notice:language配置相同\n"+JSONUtil.toJsonStr(collect)+"\n\n");
    }
}
